import { useEffect, useRef } from 'react'

function useInterval(callback, delay) {
  const savedCallback = useRef()

  // 保存新回调
  useEffect(() => {
    savedCallback.current = callback
  })

  // 建立 interval
  useEffect(() => {
    if (delay === null) {
      return
    }
    let timerId = null
    function run() {
      const returnValue = savedCallback.current()
      if (returnValue) {
        if (returnValue instanceof Function) {
          returnValue()
        } else {
          throw new Error('返回值必须是函数！')
        }
        timerId && clearTimeout(timerId)
        return
      }
      timerId = setTimeout(run, delay)
    }

    timerId = setTimeout(run, delay)
    return () => timerId && clearTimeout(timerId)
  }, [delay])
}

export default useInterval
